package org.yi.fc.helper;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.yi.fc.model.Route;
import org.yi.fc.utils.StringUtils;

public class RouteHelper {
	
	private static final String NAMESPACE = "namespace";
	private static final String ACTION = "action";
	private static final String CLAZZ = "clazz";
	
	/**
	 * 解析路由配置
	 * @param file
	 * @return
	 * @throws DocumentException
	 */
	@SuppressWarnings("unchecked")
	public static List<Route> loadRoute(File file) throws DocumentException {
        SAXReader reader = new SAXReader();
        List<Route> routes = new ArrayList<Route>();
        try {
            Document document = reader.read(file);
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            for (Element element : elementList) {
            	Route route = new Route(); 
            	for (Iterator<Node> i = element.nodeIterator(); i.hasNext();) {
                    Node node = i.next();
                    if (StringUtils.equals(node.getName(), NAMESPACE)) {
                    	route.setNamespace(node.getStringValue());
                    } else if (StringUtils.equals(node.getName(), ACTION)) {
                    	route.setAction(node.getStringValue());
                    } else if(StringUtils.equals(node.getName(), CLAZZ)) {
                    	route.setClazz(node.getStringValue());
                    }
                }
            	routes.add(route);
            }
        } catch (DocumentException e) {
        	throw new DocumentException("load route config error!");
        }
        return routes;
    }

	/**
	 * 构建Routes的ControllerKey
	 * @param r
	 * @return
	 */
	public static String getControllerKey(Route r) {
		String key = "";
		if(StringUtils.isBlank(r.getNamespace())) {
			key = r.getAction();
		} else {
			key = r.getNamespace();
			if(!key.startsWith("/")) {
				key = "/" + key;
				if(!r.getAction().startsWith("/")){
					key = key + "/" + r.getAction();
				} else {
					key = key + r.getAction();
				}
			}
		}
		return key;
	}
	
}
